package com.lx.entity;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lx.annotation.Note;
import com.lx.boot.web.valid.Check;
import com.lx.boot.web.valid.Validate;
import com.lx.util.LX;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.function.Function;

/**
 * 分页入参父类
 *
 * @author ylx
 * @date 2020-06-12
 */
@Data
@Check(function = SortPageDTO.LengthFunc.class)
public class SortPageDTO<T> extends PageDTO<T> implements Serializable {
    @Schema(description = "排序字段",required=true,example = "[\"fieldName\"]")
    private List<@Pattern(regexp= "[a-zA-Z0-9_]+",message = "排序字段只能是英文数字下划线") String> sortFields;

    @Schema(description = "排序规则 true 正序 false 倒叙",required=true,example = "[true]")
    private List<@NotNull(message = "排序规则不能为空!") Boolean> ascs;

    @Note("开始分页")
    private void startPage(){
        if (LX.isNotEmpty(ascs) && LX.isNotEmpty(sortFields)){
            for (int i = 0; i < ascs.size(); i++) {
                OrderItem orderItem = new OrderItem().setColumn(sortFields.get(i)).setAsc(ascs.get(i));
                addOrder(orderItem);
            }
        }
    }

    public void setAscs(List<Boolean> ascs) {
        this.ascs =ascs;
        startPage();
    }

    public void setSortFields(List<String> sortFields) {
        this.sortFields = sortFields;
        startPage();
    }

    @Note("判断排序字符和排序规则入参长度不一致")
    public static class LengthFunc implements Function<Validate, Boolean> {
        @Override
        public Boolean apply(Validate validate) {
            validate.setMessage("排序字符和排序规则入参长度不一致!");
            SortPageDTO t = validate.getObject();
            return validate.objIsNotNull() && (LX.getLenght(t.getSortFields()) == LX.getLenght(t.getAscs()));
        }
    }

}
